package icegps.com.pingdj.activity;


import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;

import butterknife.BindView;
import icegps.com.pingdj.R;
import icegps.com.pingdj.adapter.ScanBleAdapter;
import icegps.com.pingdj.data.ble.BleHelper;
import icegps.com.pingdj.data.ble.BleStatusCallbackImpl;

/**
 * Created by 111 on 2018/1/25.
 */

public class BleActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.ref)
    SwipeRefreshLayout ref;
    private ArrayList<BleDevice> bleDevices;
    private AlertDialog connectingDialog;
    private ScanBleAdapter scanBleAdapter;
    private BleHelper bleHelper;

    private Activity activity;
    private int OPEN_BLE = 10;

    @Override
    protected int setLayout() {
        return R.layout.activity_ble;
    }

    @Override
    protected String setTitle() {
        return getString(R.string.ble_scan);
    }

    @Override
    protected void init() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(
                Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(grand -> {
                    if (grand) {
                        activity = this;
                        initRef();
                        initRecycleViewAndRef();
                        initBle();
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        connectingDialog = builder.setView(R.layout.view_alert)
                                .create();
                        connectingDialog.setCancelable(false);
                    } else {
                        Toast.makeText(this, R.string.permissions_denied, Toast.LENGTH_SHORT).show();
                    }
                });
    }


    private void initBle() {
        bleHelper = BleHelper.getInstance();
        bleHelper.disconnectAllDevice();
        bleHelper.addBleStatusCallback(bleStatusCallback);
        if (bleHelper.isOpenBle()) {
            scan();
        } else {
            bleHelper.openBle(activity, OPEN_BLE);
        }
    }

    private void initRecycleViewAndRef() {
        bleDevices = new ArrayList<>();
        scanBleAdapter = new ScanBleAdapter(R.layout.item_device, bleDevices);
        scanBleAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(scanBleAdapter);
        scanBleAdapter.setOnItemClickListener(this);
    }

    private void initRef() {
        ref.setOnRefreshListener(this);
        ref.setColorSchemeColors(getResources().getColor(R.color.colorAccent));
    }


    @Override
    public void onRefresh() {
        bleDevices.clear();
        scanBleAdapter.notifyDataSetChanged();
        scan();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        cancelScan();
        connect(bleDevices.get(position));
        connectingDialog.show();
    }

    private void scan() {
        ref.setRefreshing(true);
        bleHelper.scan();
    }


    private void connect(BleDevice bleDevice) {
        cancelScan();
        bleHelper.connect(bleDevice);
    }

    private void cancelScan() {
        bleHelper.cancelScan();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bleHelper != null) {
            bleHelper.removeBleStatusCallback(bleStatusCallback);
        }
        cancelScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_BLE && resultCode == RESULT_OK) {
            scan();
        }
    }

    private void connectFail() {
        showToast(getString(R.string.connection_fails));
        connectingDialog.dismiss();
    }

    private void showToast(String msg) {
        Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
    }

    BleStatusCallbackImpl bleStatusCallback = new BleStatusCallbackImpl() {
        @Override
        public void onScanning(BleDevice result) {
            super.onScanning(result);
            String deviceName = result.getName();
            if (deviceName==null)return;
            if (!deviceName.startsWith("ICE"))return;
            for (BleDevice bleDevice : bleDevices) {
                if (bleDevice.getMac().equals(result.getMac())) {
                    return;
                }
            }
            ref.setRefreshing(false);
            bleDevices.add(result);
            scanBleAdapter.notifyDataSetChanged();
        }

        @Override
        public void onConnectFail(BleException exception) {
            super.onConnectFail(exception);
            connectFail();
        }

        @Override
        public void onNotifySuccess() {
            super.onNotifySuccess();
            connectingDialog.dismiss();
            showToast(getString(R.string.connection_successful));
            finish();
        }

        @Override
        public void onNotifyFailure(BleException exception) {
            super.onNotifyFailure(exception);
            connectFail();
        }

        @Override
        public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
            super.onDisConnected(isActiveDisConnected, device, gatt, status);
            connectFail();
        }
    };

}
